import { reactive, toRaw, computed, ref } from "vue";
import { message } from "@/utils/message";
import { HttpPagePar, ConditionalListType } from "@/utils/http/httpPagePar";
import { getPageDataApi, deleteApi, enableApi } from "@/api/comment";
import { getLikeTitleSelectDataApi } from "@/api/contents";
import { CmpHandleStateEnum, CmpGlobal } from "@/common/GlobalType";
import type { FormRules } from "element-plus";
import type { PaginationProps } from "@pureadmin/table";
import type { commentDto } from "@/Model/comment";

interface CmpGlobalType extends CmpGlobal {
  contentsSelectData: any[];
}
type SearchFormType = {
  contentsid: any[];
  ifdisable: string;
};

/**
 * 观看平台hook
 * @returns columns 表格头部列 {obiect} onSearch 表格搜索事件 {obiect}
 */
export function useWatch() {
  const contentsSelectLoading = ref(false);
  /** 表格头部列 */
  const columns: TableColumnList = [
    {
      type: "selection",
      width: 55,
      align: "left",
      hide: ({ checkList }) => !checkList.includes("勾选列")
    },
    {
      label: "序号",
      type: "index",
      minWidth: 70,
      hide: ({ checkList }) => !checkList.includes("序号列")
    },
    {
      label: "评论文章",
      prop: "contents.title"
    },
    {
      label: "评论内容",
      prop: "content",
      cellRenderer: ({ row }) =>
        row.content.length >= 11
          ? row.content.substring(0, 10) + ".."
          : row.content
    },
    {
      label: "是否禁用",
      prop: "ifdisable",
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={row.ifdisable === 1 ? "success" : "danger"}
          effect="plain"
        >
          {row.ifdisable === 1 ? "启用" : "禁用"}
        </el-tag>
      )
    },
    {
      label: "创建人",
      prop: "createdUsers.name"
    },
    {
      label: "更新人",
      prop: "updatedUsers.name"
    },
    {
      label: "最近更新时间",
      prop: "updatedtime"
    },
    {
      label: "操作",
      slot: "operation"
    }
  ];
  /** 组件需要全局使用的变量 */
  const cmpglobal = reactive<CmpGlobalType>({
    dialogVisible: false,
    cmpHandleState: CmpHandleStateEnum.View,
    ids: [],
    tableTitle: "评论列表",
    contentsSelectData: []
  });
  /** 更新或添加表单 */
  const addorupdataform = reactive<commentDto>({
    id: 0,
    ifdisable: 1,
    contentsid: 0,
    contentsname: "",
    parentid: 0,
    content: ""
  });
  /** 表单验证对象 */
  const rules = reactive<FormRules>({});
  /** 搜索框表单 */
  const searchform = reactive<SearchFormType>({
    contentsid: [],
    ifdisable: "1"
  });
  /** 表格绑定数据对象 */
  const tabledata: any = reactive({
    data: []
  });
  /** 分页配置 */
  const pagination = reactive<PaginationProps>({
    pageSize: 10,
    currentPage: 1,
    pageSizes: [10, 15, 20],
    total: 0,
    align: "center",
    background: true,
    small: false
  });
  /** dialog标题 */
  const dialogtitle = computed(() => {
    let res = "";
    switch (cmpglobal.cmpHandleState) {
      case CmpHandleStateEnum.Add:
        res = "新增";
        break;
      case CmpHandleStateEnum.Updata:
        res = "修改";
        break;
      default:
        res = "查看";
        break;
    }
    return res;
  });
  /** 表单输入框是否禁用 */
  const ifDisabledForm = computed(() => {
    if (cmpglobal.cmpHandleState === CmpHandleStateEnum.View) {
      return true;
    } else {
      return false;
    }
  });

  /** api数据请求体 */
  const httpPagePar = new HttpPagePar();

  /**
   * 向服务器请求表格数据
   */
  function getPageData() {
    httpPagePar.pageNum = pagination.currentPage;
    httpPagePar.pageSize = pagination.pageSize;
    const conditionallist: ConditionalListType[] = [];
    if (searchform.contentsid.length > 0) {
      const item: ConditionalListType = {
        key: 0,
        value: {
          fieldName: "contentsid",
          fieldValue: searchform.contentsid[0] + "",
          cSharpTypeName: "long",
          conditionalType: 0
        }
      };
      conditionallist.push(item);
    }
    if (searchform.ifdisable === "0" || searchform.ifdisable === "1") {
      const item: ConditionalListType = {
        key: 0,
        value: {
          fieldName: "ifdisable",
          fieldValue: searchform.ifdisable,
          cSharpTypeName: "long",
          conditionalType: 0
        }
      };
      conditionallist.push(item);
    }
    if (conditionallist.length > 0) {
      httpPagePar.conditionalList = conditionallist;
    } else {
      httpPagePar.conditionalList = [];
    }
    httpPagePar.orderBys = ["id desc"];

    getPageDataApi(httpPagePar)
      .then(res => {
        if (res.code === 1) {
          tabledata.data = res.data.data;
          pagination.total = res.data.total;
        } else {
          message(res.msg, { type: "error" });
          tabledata.data = [];
          pagination.total = 0;
        }
      })
      .catch(err => {
        message(`获取表格数据失败:${err}`, { type: "error" });
        console.log(err);
      });
  }

  /**
   * 搜索事件
   */
  const clickSearch = () => {
    pagination.currentPage = 1;
    getPageData();
  };
  /**
   * 分页控件选择显示多少条数据事件
   */
  function onSizeChange(val) {
    pagination.pageSize = val;
    //重新获取数据
    getPageData();
  }
  /**
   * 分页控件选择页码事件
   */
  function onCurrentChange(val) {
    pagination.currentPage = val;
    //重新获取数据
    getPageData();
  }

  /**
   * 表格的刷新事件
   */
  function onSearch() {
    //重新获取数据
    getPageData();
  }
  /**
   * 表格查看事件
   * @param row 选中数据
   */
  function handleView(row) {
    cmpglobal.cmpHandleState = CmpHandleStateEnum.View;
    cmpglobal.dialogVisible = true;
    SetFormData(row);
  }

  /**
   * 网络请求禁用数据
   * @param params id数组
   */
  function Delete(params: number[]) {
    deleteApi({ ids: params })
      .then(res => {
        if (res.code === 1) {
          message(res.msg, { type: "success" });
          //更新数据
          getPageData();
        } else {
          message(res.msg, { type: "error" });
        }
        cmpglobal.ids = [];
      })
      .catch(err => {
        cmpglobal.ids = [];
        message(`禁用失败:${err}`, { type: "error" });
        console.log(err);
      });
  }
  /**
   * 网络请求禁用数据
   * @param params id数组
   */
  function Enable(params: number[]) {
    enableApi({ ids: params })
      .then(res => {
        if (res.code === 1) {
          message(res.msg, { type: "success" });
          //更新数据
          getPageData();
        } else {
          message(res.msg, { type: "error" });
        }
        cmpglobal.ids = [];
      })
      .catch(err => {
        cmpglobal.ids = [];
        message(`禁用失败:${err}`, { type: "error" });
        console.log(err);
      });
  }
  /**
   * 表格删除事件
   * @param row 选中数据
   */
  function handleDelete(row) {
    Delete([row.id]);
  }
  /**
   * 表格启用事件
   * @param row 选中数据
   */
  function handleEnable(row) {
    Enable([row.id]);
  }
  /**
   * 批量删除
   */
  function handleBatchDelete() {
    if (cmpglobal.ids.length <= 0) {
      message("请选择需要禁用的数据", { type: "error" });
    } else {
      Delete(toRaw(cmpglobal.ids));
    }
  }
  /**
   * 批量启用
   */
  function handleBatchEnable() {
    if (cmpglobal.ids.length <= 0) {
      message("请选择需要禁用的数据", { type: "error" });
    } else {
      Enable(toRaw(cmpglobal.ids));
    }
  }
  /**
   * 表格选择列的事件
   * @param val 选中数据
   */
  function handleSelectionChange(val) {
    if (val.length > 0) {
      const selectids: number[] = [];
      val.forEach(function (item) {
        selectids.push(item.id);
      });
      cmpglobal.ids = selectids;
    }
  }

  /**
   * 重置搜索表单
   */
  function resetSearchForm() {
    searchform.contentsid = [];
    searchform.ifdisable = "";
    getPageData();
  }
  /**
   * 设置表单数据
   * @param row 行数据
   */
  function SetFormData(row: any) {
    addorupdataform.id = row.id;
    addorupdataform.ifdisable = row.ifdisable;
    addorupdataform.contentsid = row.contentsid;
    addorupdataform.contentsname = row.contents.title;
    addorupdataform.parentid = row.parentid;
    addorupdataform.content = row.content;
  }
  /**
   * dialog对话框关闭回调函数
   */
  function dialogClose() {}
  const contentsSelectRemoteMethod = (query: string) => {
    if (query) {
      contentsSelectLoading.value = true;
      getLikeTitleSelectDataApi(query)
        .then(res => {
          if (res.code === 1) {
            cmpglobal.contentsSelectData = res.data;
            contentsSelectLoading.value = false;
          } else {
            message(res.msg, { type: "error" });
            contentsSelectLoading.value = false;
            console.log(res);
          }
        })
        .catch(err => {
          contentsSelectLoading.value = false;
          message("获取文章数据失败:" + err, { type: "error" });
          console.log(err);
        });
    } else {
      cmpglobal.contentsSelectData = [];
    }
  };
  return {
    columns,
    onSearch,
    searchform,
    tabledata,
    getPageData,
    handleView,
    handleDelete,
    handleSelectionChange,
    handleBatchDelete,
    handleBatchEnable,
    cmpglobal,
    dialogtitle,
    addorupdataform,
    resetSearchForm,
    rules,
    pagination,
    onSizeChange,
    onCurrentChange,
    clickSearch,
    dialogClose,
    handleEnable,
    ifDisabledForm,
    contentsSelectLoading,
    contentsSelectRemoteMethod
  };
}
